<template>
  <div :class="['history-panel', { 'collapsed': isCollapsed }]">
    <!-- 折叠按钮 -->
    <div class="toggle-button" @click="toggleCollapse">
      <el-icon :class="['toggle-icon', { 'rotated': isCollapsed }]" size="20" color="#D4AF37">
        <ArrowLeft />
      </el-icon>
    </div>
    
    <!-- 面板内容 -->
    <div v-if="!isCollapsed" class="panel-content">
      <div class="panel-header">
        <el-icon class="history-icon" size="20" color="#D4AF37">
          <ChatDotSquare />
        </el-icon>
        <h3 class="panel-title">对话记录</h3>
      </div>
      
      <div class="panel-actions">
        <el-button 
          type="primary" 
          size="small" 
          @click="$emit('create-session')"
          class="new-chat-btn"
        >
          <el-icon size="14"><Plus /></el-icon>
          新对话
        </el-button>
      </div>
      
      <div class="history-list" ref="historyContainer" @scroll="handleScroll">
        <div 
          v-for="(session, index) in displayedSessions" 
          :key="session.id"
          :class="['history-item', { 'active': currentSessionId === session.id }]"
        >
          <div class="history-content" @click="$emit('load-session', session.id)">
            <div class="history-header">
              <el-icon class="session-icon" size="14" color="#8B4513">
                <UserFilled />
              </el-icon>
              <span class="history-character">{{ session.character || '未知角色' }}</span>
            </div>
            <div class="history-title">{{ session.title }}</div>
            <div class="history-meta">
              <span class="history-time">{{ formatTime(session.startTime) }}</span>
              <span class="history-count">{{ session.messageCount }}条</span>
            </div>
          </div>
          
          <div class="history-actions">
            <el-button
              type="danger"
              size="small"
              circle
              @click.stop="$emit('delete-session', session.id)"
              class="delete-btn"
            >
              <el-icon size="12"><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        
        <!-- 加载更多指示器 -->
        <div v-if="hasMore && displayedSessions.length > 0" class="load-more">
          <el-icon class="loading-icon" size="16" color="#D4AF37">
            <Loading />
          </el-icon>
          <span class="load-text">滚动加载更多...</span>
        </div>
        
        <div v-if="chatSessions.length === 0" class="empty-state">
          <el-icon size="48" color="#CCCCCC">
            <ChatDotSquare />
          </el-icon>
          <p class="empty-text">暂无对话记录</p>
          <p class="empty-hint">选择角色开始新的魔法对话</p>
        </div>
      </div>
    </div>
    
    <!-- 折叠状态的简化显示 -->
    <div v-else class="collapsed-content">
      <div class="collapsed-icon">
        <el-icon size="24" color="#D4AF37">
          <ChatDotSquare />
        </el-icon>
      </div>
      <div class="collapsed-count">{{ chatSessions.length }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { 
  ArrowLeft, 
  ChatDotSquare, 
  Plus, 
  UserFilled, 
  Delete,
  Loading
} from '@element-plus/icons-vue'

const props = defineProps({
  chatSessions: {
    type: Array,
    default: () => []
  },
  currentSessionId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits([
  'load-session',
  'create-session',
  'delete-session'
])

const isCollapsed = ref(false)
const pageSize = 8 // 每页显示8条记录
const currentPage = ref(1)
const historyContainer = ref(null)

// 计算显示的对话记录
const displayedSessions = computed(() => {
  const endIndex = currentPage.value * pageSize
  return props.chatSessions.slice(0, endIndex)
})

// 是否还有更多记录
const hasMore = computed(() => {
  return props.chatSessions.length > displayedSessions.value.length
})

// 监听chatSessions变化，重置分页
watch(() => props.chatSessions, () => {
  currentPage.value = 1
}, { deep: true })

// 切换折叠状态
function toggleCollapse() {
  isCollapsed.value = !isCollapsed.value
}

// 处理滚动事件
function handleScroll() {
  if (!historyContainer.value || !hasMore.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = historyContainer.value
  
  // 当滚动到底部附近时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 50) {
    loadMore()
  }
}

// 加载更多记录
function loadMore() {
  if (hasMore.value) {
    currentPage.value += 1
  }
}

// 格式化时间 - 缓存结果避免频繁计算
const timeCache = new Map()

function formatTime(timeString) {
  if (!timeString) return ''
  
  // 检查缓存
  if (timeCache.has(timeString)) {
    return timeCache.get(timeString)
  }
  
  const date = new Date(timeString)
  const now = new Date()
  const diffMs = now - date
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  let result = ''
  if (diffDays === 0) {
    result = date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  } else if (diffDays === 1) {
    result = '昨天'
  } else if (diffDays < 7) {
    result = `${diffDays}天前`
  } else {
    result = date.toLocaleDateString('zh-CN', { 
      month: 'short', 
      day: 'numeric' 
    })
  }
  
  // 缓存结果
  timeCache.set(timeString, result)
  return result
}
</script>

<style scoped>
.history-panel {
	position: relative;
	background: white;
	/* 使用简单的分割线 */
	border-right: 1px solid #e0e0e0;
	transition: all 0.3s ease;
	width: 280px;
	display: flex;
	flex-direction: column;
	/* 移除圆角、阴影和边距，完全贴合 */
}

.history-panel.collapsed {
  width: 60px;
}

.toggle-button {
  position: absolute;
  top: 50%;
  right: -15px;
  transform: translateY(-50%);
  z-index: 100;
  width: 30px;
  height: 30px;
  background: #D4AF37;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.toggle-button:hover {
  background: #FFD700;
  transform: translateY(-50%);
  filter: brightness(1.1);
}

.toggle-icon {
  transition: transform 0.3s ease;
}

.toggle-icon.rotated {
  transform: rotate(180deg);
}

.panel-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.panel-title {
  font-size: 18px;
  font-weight: 600;
  color: #8B4513;
  margin: 0;
}

.panel-actions {
  margin-bottom: 16px;
}

.new-chat-btn {
  width: 100%;
  border-radius: 20px;
  font-weight: 500;
  background: linear-gradient(135deg, #D4AF37, #FFD700);
  border: none;
  transition: all 0.3s ease;
}

.new-chat-btn:hover {
  box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3);
  filter: brightness(1.05);
}

.history-list {
  height: 400px; /* 固定高度 */
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-right: 4px; /* 为滚动条留空间 */
}

.history-item {
  display: flex;
  align-items: stretch;
  background: #FAFAFA;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  min-height: 80px; /* 设置最小高度 */
  flex-shrink: 0; /* 防止被压缩 */
}

.history-item:hover {
  background: #F0F8FF;
  border-color: #D4AF37;
  box-shadow: 0 2px 8px rgba(212, 175, 55, 0.2);
}

.history-item.active {
  background: linear-gradient(135deg, #D4AF37, #FFD700);
  color: white;
  border-color: #B8860B;
}

.history-content {
  flex: 1;
  padding: 12px;
  cursor: pointer;
}

.history-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}

.history-character {
  font-size: 12px;
  font-weight: 600;
  color: #8B4513;
}

.history-item.active .history-character {
  color: rgba(255, 255, 255, 0.9);
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
  line-height: 1.3;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-item.active .history-title {
  color: white;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #666;
}

.history-item.active .history-meta {
  color: rgba(255, 255, 255, 0.8);
}

.history-actions {
  display: flex;
  align-items: center;
  padding: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.history-item:hover .history-actions {
  opacity: 1;
}

.delete-btn {
  background: #ff4757;
  border: none;
}

.delete-btn:hover {
  background: #ff3838;
  filter: brightness(1.1);
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  color: #8B4513;
  font-size: 12px;
  opacity: 0.7;
  flex-shrink: 0;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.empty-text {
  margin: 16px 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.empty-hint {
  margin: 0;
  font-size: 14px;
  opacity: 0.7;
}

.collapsed-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px 0;
}

.collapsed-icon {
  margin-bottom: 8px;
}

.collapsed-count {
  background: #D4AF37;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
}

/* 滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track {
  background: transparent;
}

.history-list::-webkit-scrollbar-thumb {
  background: #D4AF37;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover {
  background: #B8860B;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-panel {
    width: 240px;
  }
  
  .panel-content {
    padding: 16px;
  }
  
  .history-list {
    height: 350px; /* 移动端稍微小一点 */
  }
  
  .history-item {
    min-height: 70px;
  }
}

@media (max-width: 480px) {
  .history-panel {
    width: 200px;
  }
  
  .panel-content {
    padding: 12px;
  }
  
  .history-list {
    height: 300px;
  }
  
  .history-item {
    min-height: 65px;
    margin-bottom: 6px;
  }
}
</style>
